import axios from "axios";
import {ElMessageBox} from "element-plus";
import {getToken, removeToken} from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_ORIGN_API, // 代理路径
  // baseURL: "http://localhost:8000/api/",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

      if (getToken()) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["token"] = getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    //console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom status
   * Here is just an user
   * You can also judge the status by HTTP Status status
   */
  response => {
    // 判断响应是否为二进制
    if (!response.headers["content-type"].includes("application/json")) {
      return response;
    }
    // 获取请求信息
    const { data } = response;
    // 非法授权
      if (data.status == 508) {
      ElMessageBox({
        message: "当前登录信息已过期!请重新登录",
        type: "error",
        duration: 5 * 1000,
        showClose: true
      });
      // 删除token
      removeToken();
      } else if (data.status == 401) {
          ElMessageBox({
              message: "账号或密码输入错误!",
              type: "error",
              duration: 5 * 1000,
              showClose: true
          });
          // 删除token
          removeToken();
      }
      // 非法授权
      else if (data.status === 403) {
          ElMessageBox({
              message: "对不起,您无权访问!",
              type: "error",
              duration: 5 * 1000,
              showClose: true
          });
    }
    // 发出错误信息
    else if (data.status !== 200) {
      ElMessageBox({
        message: data.message || "请求失败!",
        type: "error",
        duration: 5 * 1000,
        showClose: true
      });
      return Promise.reject(new Error(data.message || "请求错误!"));
    } else {
      return data;
    }
  },
  error => {
    const { data } = error.response;
    //console.log(error.response); // for debug
    ElMessageBox({
      message: data.message || "服务器异常!",
      type: "error",
      duration: 5 * 1000,
      showClose: true
    });
    return Promise.reject(error);
  }
);

export default service;
